package com.dmall.play.interview.chapter09;

/**
 * 记忆化搜索
 * @author xiao1.wang
 * @date 2021-01-20 10:07:45
 */
public class Leetcode64V4 {

    private int row, col;
    private Integer[][] dp;

    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        row = grid.length;
        col = grid[0].length;
        dp = new Integer[row][col];
        dp[0][0] = grid[0][0];
        for (int i = 1; i < col; i++) {
            dp[0][i] = dp[0][i - 1] + grid[0][i];
        }
        for (int i = 1; i < row; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }
        return dp[row - 1][col - 1];
    }

    public static void main(String[] args) {
        Leetcode64V4 leetcode64 = new Leetcode64V4();
        int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
        // int[][] grid = {{1, 2}, {1, 1}};
        System.out.println(leetcode64.minPathSum(grid));
    }
}
